package com.wooophone.webapp.admin.web.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.wooophone.common.util.JsonSfUtil;
import com.wooophone.common.web.action.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.wooophone.mpyeah.biz.BrandBiz;
import com.wooophone.mpyeah.biz.BrandCategoryBiz;
import com.wooophone.mpyeah.entity.Brand;
import com.wooophone.mpyeah.entity.BrandCategory;

public class BrandCategoryAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private BrandCategory brandCategory;
	private List<BrandCategory> brandCategoryList;
	private BrandCategoryBiz brandCategoryBiz;
	// private FileInfo fileInfo;
	private BrandBiz brandBiz;
	private String gradeField;
	private String parentId;
	private String parentName;
	private String ids;

	private String filePath;
	private String uploadContentType;
	private String uploadFileName;

	public String list() {
		try {
			brandCategoryList = brandCategoryBiz.list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, Integer> treeMap = new HashMap<String, Integer>();
		for (int i = 0; i < brandCategoryList.size(); i++) {
			treeMap.put(brandCategoryList.get(i).getId(), i + 1);
		}

		ActionContext.getContext().put("treeMap", treeMap);
		return SUCCESS;
	}

	public String sort_list() {
		try {
			if (parentId == null) {
				brandCategoryList = brandCategoryBiz.findTopCategory();
			} else {
				Map<String, Object> parameter = new HashMap<String, Object>();
				parameter.put("parentId", parentId);
				brandCategoryList = brandCategoryBiz.findByParentId(parentId);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}

		return SUCCESS;
	}

	public String input() {
		try {

			if (id != null && !"".equals(id)) {
				brandCategory = brandCategoryBiz.get(id);
				parentId = brandCategory.getId();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	public String view() {
		brandCategory = brandCategoryBiz.get(id);
		List<Object> list = brandCategory.getNonceGrandeField();
		if (list == null)
			brandCategory.setNonceGrandeField(new ArrayList<Object>());
		return SUCCESS;
	}

	public String save() {
		try {
			brandCategory.setParentId(parentId);
			brandCategory.setIcon(filePath);
			brandCategory.setGradeField(this.resetGradeField(brandCategory
					.getGradeField()));// 替换分类属性中的中文"，"
			brandCategory.setCreator(ServletActionContext.getRequest()
					.getUserPrincipal().getName());
			if (brandCategory.getName() != null
					|| !"".equals(brandCategory.getName())) {

				brandCategoryBiz.save(brandCategory);
				if (brandCategory != null && brandCategory.getId() != null) {
					this.sendUrl = "brand_list.action";
					return SUCCESS;
				} else {
					return error(getText("brandCategory.save.error"));
				}

			} else {
				return error(getText("brandCategory.save.error"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return error(getText("brandCategory.save.exception"));
		}
	}

	public String saveSort() {

		try {
			String[] idList = null;
			ids.trim();
			int lastIndex = ids.lastIndexOf(",");
			if (lastIndex == ids.length() - 1) {
				ids = ids.substring(0, lastIndex);
			}
			idList = ids.split(",");
			if (idList != null) {
				for (int i = 0; i < idList.length; i++) {
					System.out.println(idList[i]);
					brandCategory = brandCategoryBiz.get(idList[i]);
					brandCategory.setSortOrder(i);
					brandCategoryBiz.update(brandCategory);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ajax(Status.error, "保存失败");
		}

		return ajax(Status.success, "保存成功");
	}

	@RequiredStringValidator(fieldName = "id", key = "noid", message = "no id")
	public boolean vlidataCategoryIsExistBrand() {
		Map<String, Object> parameter = new HashMap<String, Object>();
		parameter.put("parentId", id);
		List<BrandCategory> brandCategorieList = brandCategoryBiz
				.find(parameter);
		if (brandCategorieList != null) {
			if (brandCategorieList.size() > 0) {
				return true;
			} else {
				parameter.clear();
				parameter.put("cid", id);
				List<Brand> list = brandBiz.find(parameter);
				if (list != null) {
					if (list.size() > 0) {
						return true;
					}
				}
			}
		}
		return false;

	}

	@RequiredStringValidator(fieldName = "id", key = "noid", message = "no id")
	public String delete() {
		boolean flag = vlidataCategoryIsExistBrand();
		if (flag) {
			return ajax("[{'status':'yes','message':'"
					+ getText("brandCategory.validata.existBrand") + "'}]");
		}
		try {
			if (brandCategoryBiz.delete(id) > 0) {
				return ajax("[{'status':'success','message':'"
						+ getText("brandCategory.delete.success") + "'}]");
			} else {
				return ajax("[{'status':'error','message':'"
						+ getText("brandCategory.delete.error") + "'}]");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ajax("[{'status':'error','message':'"
					+ getText("brandCategory.delete.exception") + "'}]");
		}
	}

	@RequiredStringValidator(fieldName = "id", key = "noid", message = "no id")
	public String edit() {
		try {
			brandCategory = brandCategoryBiz.get(id);
			parentId = brandCategory.getParentId();
			String gradeFieldStr = brandCategory.getGradeField();
			if (gradeFieldStr != null && !"".equals(gradeFieldStr)) {
				gradeFieldStr = gradeFieldStr.substring(1);
				gradeFieldStr = gradeFieldStr.substring(0,
						gradeFieldStr.indexOf("]"));
				gradeFieldStr=gradeFieldStr.replace("\"", "");
				gradeFieldStr.trim();
				gradeField = gradeFieldStr;
			} else {
				gradeField = "";
			}
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR_PAGE;
		}

	}

	public String update() {
		BrandCategory brandCategoryOld = null;
		try {
			if (brandCategory.getId() != null
					&& !"".equals(brandCategory.getId())) {
				brandCategoryOld = brandCategoryBiz.get(brandCategory.getId());
				brandCategoryOld.setName(brandCategory.getName());
				brandCategoryOld.setDescription(brandCategory.getDescription());
				brandCategoryOld.setMore(brandCategory.getMore());
				brandCategoryOld.setGradeField(brandCategory.getGradeField());
			}
			if (parentId != null && !"".equals(parentId)) {
				brandCategoryOld.setParentId(parentId);
			}
			if(filePath!=null&&!"".equals(filePath)){
				brandCategoryOld.setIcon(filePath);
			}
			brandCategoryOld.setGradeField(this.resetGradeField(brandCategory
					.getGradeField()));// 替换分类属性中的中文"，"
			int r = brandCategoryBiz.update(brandCategoryOld);
			if (r > 0) {
				return SUCCESS;
			} else {
				return error(getText("brandCategory.update.error"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR_PAGE;
		}

	}

	private String resetGradeField(String gradeField) {
		if (gradeField == null)
			return null;
		gradeField = gradeField.trim();
		gradeField = gradeField.replace("，", ",");
		if (gradeField.indexOf(",") == 0) {
			gradeField = gradeField.substring(1);
		}
		if (gradeField.lastIndexOf(",") == gradeField.length() - 1
				&& gradeField.length() > 0) {
			gradeField = gradeField.substring(0, gradeField.length());
		}
		String[] str = gradeField.split(",");
		List<String> list = new ArrayList<String>();
		for (String string : str) {
			list.add(string);
		}
		gradeField = JsonSfUtil.toJsonByJsonLib(list);
		return gradeField;
	}

	public List<BrandCategory> getBrandCategoryList() {
		return brandCategoryList;
	}

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	public String getParentName() {
		return parentName;
	}

	public void setParentName(String parentName) {
		this.parentName = parentName;
	}

	public void setBrandCategory(BrandCategory brandCategory) {
		this.brandCategory = brandCategory;
	}

	public void setBrandCategoryBiz(BrandCategoryBiz brandCategoryBiz) {
		this.brandCategoryBiz = brandCategoryBiz;
	}

	public void setBrandBiz(BrandBiz brandBiz) {
		this.brandBiz = brandBiz;
	}

	public BrandCategory getBrandCategory() {
		return brandCategory;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getGradeField() {
		return gradeField;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

}
